import {
  updateTopic,
  getTopicById,
} from "~/server/database/services/topicService";
import { TopicDomain, Difficulty } from "~/server/database/models/Topic";
import authMiddleware from "~/server/middleware/auth";

export default defineEventHandler(async (event) => {
  try {
    // 使用认证中间件获取用户信息
    await authMiddleware(event);

    const id = getRouterParam(event, "id");
    const body = await readBody(event);

    if (!id || isNaN(parseInt(id))) {
      throw createError({
        statusCode: 400,
        statusMessage: "无效的题目ID",
      });
    }

    // 验证枚举值（如果提供）
    if (body.domain && !Object.values(TopicDomain).includes(body.domain)) {
      throw createError({
        statusCode: 400,
        statusMessage: "无效的领域值",
      });
    }

    if (
      body.difficulty &&
      !Object.values(Difficulty).includes(body.difficulty)
    ) {
      throw createError({
        statusCode: 400,
        statusMessage: "无效的难度值",
      });
    }

    // 从event.context中获取用户信息
    const user = event.context.user;

    // 检查题目是否存在并验证权限
    const existingTopic = await getTopicById(parseInt(id));

    if (!existingTopic) {
      throw createError({
        statusCode: 404,
        statusMessage: "题目不存在",
      });
    }

    // 检查是否有权限修改此题目
    if (existingTopic?.dataValues.submitterId !== user.id) {
      throw createError({
        statusCode: 403,
        statusMessage: "无权修改此题目",
      });
    }

    // 更新题目
    const topic = await updateTopic(parseInt(id), body);

    if (!topic) {
      throw createError({
        statusCode: 404,
        statusMessage: "题目不存在",
      });
    }

    return {
      success: true,
      data: topic,
      message: "题目更新成功",
    };
  } catch (error) {
    console.error("更新题目失败:", error);

    if (error && typeof error === "object" && "statusCode" in error) {
      throw error;
    }

    throw createError({
      statusCode: 500,
      statusMessage: "更新题目失败",
    });
  }
});
